import axios from 'axios'
import qs from 'qs'
import store from "./store";
import {data} from "autoprefixer";
import {config} from "shelljs";
import {promise} from "ora";
import da from "element-ui/src/locale/lang/da";

let http = axios.create({
  baseURL: 'http://localhost:7000',
  method: 'POST',
  //携带凭证
  withCredentials: true

})

//请求拦截器
http.interceptors.request.use(requestConfig => {

  if (requestConfig.method == 'post') {
    requestConfig.headers['Context-Type'] = "application/x-www-form-urlencoded"
    requestConfig.data = qs.stringify(requestConfig.data);
  }
  //获取token数据
  let token = sessionStorage.getItem("token")
  if (token != null) {
    token = qs.parse(token);
    requestConfig.headers = {
      'Content-Type': "application/x-www-form-urlencoded",
      'Authorization': token.token_type + ' ' + token.access_token
    }
  }
  return requestConfig

})


//拦截然后响应

http.interceptors.response.use(response => {
   let data = response.data
   let code = data.code;
  //判断是令牌过期
  if (code==204){
    console.log("token过期")
    let data=qs.parse(sessionStorage.getItem("token"));
    //进入接口，用刷新码,获取新的token
    let responseResult=http.post("authserver/oauth/token",{
      grant_type: 'refresh_token',
      client_id: store.state.client.client_id,
      client_secret: store.state.client.client_secret,
      refresh_token: data.refresh_token
    }).then(data=>{
      //把值更新
      sessionStorage.setItem("token",qs.stringify(data))
      return error.config
    }).then(config=>{
      //重新发送请求
      return http(config)
    })
    return responseResult
  }
  return response.data
},error => {
  return  Promise.reject(error)
})

export default http
